package com.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pojo.Menu;
import com.pojo.Role;
import com.service.MenuService;
import com.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;

    @GetMapping("/list")
    public String list(@RequestParam(defaultValue = "1") int pageNum,
                       @RequestParam(defaultValue = "5") int pageSize,
                       Model model) {
        PageHelper.startPage(pageNum, pageSize);
        List<Role> roles = roleService.findAll();
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        model.addAttribute("pageInfo", pageInfo);
        return "role/roleList";
    }

    @GetMapping("/add")
    public String addPage() {
        return "role/roleAdd";
    }

    @PostMapping("/insert")
    public String insert(Role role) {
        roleService.insert(role);
        return "redirect:/role/list";
    }

    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Integer id, Model model) {
        Role role = roleService.findById(id);
        model.addAttribute("role", role);
        return "role/roleEdit";
    }

    @PostMapping("/update")
    public String update(Role role) {
        roleService.update(role);
        return "redirect:/role/list";
    }

    @GetMapping("/delete/{id}")
    public String deleteRole(@PathVariable Integer id) {
        roleService.deleteById(id);
        return "redirect:/role/list";
    }


    @GetMapping("/assignMenus/{roleId}")
    public String assignMenus(@PathVariable Integer roleId, Model model) {
        Role role = roleService.findById(roleId);
        List<Menu> menus = menuService.findAll();
        List<Integer> assignedMenuIds = roleService.getAssignedMenuIds(roleId);
        model.addAttribute("role", role);
        model.addAttribute("menus", menus);
        model.addAttribute("assignedMenuIds", assignedMenuIds);
        return "role/roleAssignMenus";
    }

    @PostMapping("/saveAssignedMenus")
    public String saveAssignedMenus(@RequestParam Integer roleId, @RequestParam List<Integer> menuIds) {
        roleService.saveAssignedMenus(roleId, menuIds);
        return "redirect:/role/list";
    }

}
